<?php
/**
 * Created By PhpStorm
 * Author: patrick wu
 * Date: 2020/9/19
 * Time: 16:16
 */
namespace App\Http\Model\Mysql;

use Illuminate\Database\Eloquent\Model;
use Laravel\Scout\Searchable;

class ProductModel extends Model
{
    const IS_DELETE =   1,      //是否删除
          NOT_DELETE=   0;

    const IS_SHELF  =   1,      //是否上架
          NOT_SHELF =   0;

    const IS_HOT    =   1,      //是否热卖
          NOT_HOT   =   0;


    protected $table    =   'mini_product';

    protected $dateFormat   =   'U';

    protected $guarded  =   [];

    /**
     * 获取模型的可搜索数据
     *
     * @return array
     */
    public function toSearchableArray()
    {
        $data   =   [
            'id'    =>  $this->id,
            'name'  =>  $this->name,
            'sku_code'  =>  $this->sku_code,
            'sell_price'=>  $this->sell_price,
            'cost_price'=>  $this->cost_price,
            'is_shelf'  =>  $this->is_shelf,
            'is_hot'    =>  $this->is_hot,
            'is_member' =>  $this->is_member,
            'desc'      =>  $this->desc
        ];

        return $data;
    }

    /**
     * 设置索引中type
     * @return string
     */
    public function searchableAs()
    {
        return '_doc';
    }

    /**
     * 搜索售卖商品
     * @param $query
     * @param array $condition
     */
    public function scopeSell($query, $condition = [])
    {
        $query->where(array_merge(['is_shelf' => self::IS_SHELF, 'is_delete' => self::NOT_DELETE], $condition));
    }

    /**
     * 定义链接静态资源表
     * @return \Illuminate\Database\Eloquent\Relations\HasMany
     */
    public function objectUrl()
    {
        return $this->hasMany(ProductObjectModel::class, 'product_id', 'id');
    }

    /**
     * 定义链接店铺表
     * @return \Illuminate\Database\Eloquent\Relations\HasOne
     */
    public function shop()
    {
        return $this->hasOne(ShopModel::class, 'id', 'shop_id');
    }

    /**
     * 定义链接品牌表
     * @return \Illuminate\Database\Eloquent\Relations\HasOne
     */
    public function brand()
    {
        return $this->hasOne(BrandModel::class, 'id', 'brand_id');
    }

    /**
     * 定义链接多个分类表
     * @return \Illuminate\Database\Eloquent\Relations\HasMany
     */
    public function category()
    {
        return $this->hasMany(ProductCatModel::class, 'product_id', 'id');
    }

    /**
     * 定义链接多个规格表
     * @return \Illuminate\Database\Eloquent\Relations\HasMany
     */
    public function specs()
    {
        return $this->hasMany(ProductSpecsModel::class, 'product_id', 'id');
    }

}
